package live.jipiao.dao;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import live.common.AirParam;
import live.common.ErrorException;
import live.common.Format;
import live.common.Verifystring;
import live.jipiao.entity.AirData;
import live.jipiao.entity.AirQuery;
import live.jipiao.entity.RateInfos;
import live.jipiao.entity.AirData.FlightItem;
import live.jipiao.entity.AirData.FlightItem.CabinItem;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;


public class QueryFlights {
	private XmlFormart xfm = new XmlFormart();
	private Verifystring verify = new Verifystring();
	private String result = null;
	private Document document = null;
	private List<FlightItem> flightList = null;
	private List<CabinItem> cabinList = null;
	private FlightItem flightItem = null;
	private CabinItem cabinItem = null;
	private QueryRates queryRate = null;
	private AirData data = null;

	/**
	 * 返回查询结果
	 * 
	 * @param query
	 * @return
	 * @throws ErrorException
	 * @throws IOException
	 * @throws DocumentException
	 * @throws SQLException
	 */
	public AirData getFlights(AirQuery query) throws ErrorException,
			IOException, DocumentException, SQLException {
		result = returnWebServiceResult(query);
		if (result != null) {
			document = xfm.xmlToDocument(result);
			queryRate = new QueryRates();
			String success = ((Element) document.selectNodes("//is_success")
					.get(0)).getTextTrim();
			if (success.trim().equals("T")) {
				List<RateInfos> rates = queryRate.getPixRates(query);
				data = new AirData();
				data.setDistance(xfm.returnSingleNode(document, "//Distance"));
				data.setFullFare(xfm.returnSingleNode(document, "//FullFare"));
				List<Element> list = xfm.returnElements(document,
						"//FlightList/*");
				FlightItem fi = null;
				if (Format.getInstance().isNotNullOrZeroForList(list)) {
					flightList = new ArrayList();
					for (Element eleObj : list) {
						flightItem = getFlightItem(eleObj,
								data.getFlightItem(), rates, query
										.getCabinUsed());
						if (flightItem.getCabinList() != null
								&& flightItem.getCabinList().size() > 0) {
							flightList.add(flightItem);
						}
					}
					data.setFlightList(flightList);
				}
			} else {
				throw new ErrorException(QueryFlights.class+";Mehtod"+JSONObject.fromObject(query)+"__"+document.selectSingleNode("//error")
						.getText());
			}
		}
		return data;
	}

	/**
	 * 过滤航班信息
	 * 
	 * @param ele
	 * @param item
	 * @param rates
	 * @param cabinLevel
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public FlightItem getFlightItem(Element ele, FlightItem item,
			List<RateInfos> rates, String cabinLevel)
			throws UnsupportedEncodingException {
		item.setStop(ele.elementText("Stop"));
		item.setTax(ele.elementTextTrim("Tax"));
		item.setYq(ele.elementTextTrim("YQ"));
		item.setFlightNo(ele.elementTextTrim("FlightNo"));
		item.setDepTime(Format.getInstance().stringToDate(
				ele.elementTextTrim("DepTime"), "yyyy-MM-dd HH:mm:ss"));
		item.setArrTime(Format.getInstance().stringToDate(
				ele.elementTextTrim("ArrTime"), "yyyy-MM-dd HH:mm:ss"));
		item.setScity(ele.elementTextTrim("Scity"));
		item.setScityName(Format.getInstance().decoedGB2312(
				ele.elementTextTrim("ScityName")));
		item.setEcity(ele.elementTextTrim("Ecity"));
		item.setEcityName(Format.getInstance().decoedGB2312(
				ele.elementTextTrim("EcityName")));
		item.setAircom(ele.elementTextTrim("Aircom"));
		item.setAircomName(Format.getInstance().decoedGB2312(
				ele.elementTextTrim("AircomName")));
		item.setIsShare(ele.elementTextTrim("IsShare"));
		item.setModel(ele.elementTextTrim("Model"));
		List<Element> nodes = ele
				.selectNodes(".//CabinList/*[Seat>0 and Fare>0]");
		if (nodes.size() > 0) {
			cabinList = new ArrayList();
			int rownum = 1;
			for (Element objCabin : nodes) {
				cabinItem = item.getCabinItem();
				cabinItem.setCode(objCabin.elementTextTrim("Code"));
				cabinItem.setDiscount(objCabin.elementTextTrim("Discount"));
				cabinItem.setFare(objCabin.elementTextTrim("Fare"));
				cabinItem.setSeat(objCabin.elementTextTrim("Seat"));
				cabinItem.setLevel(objCabin.elementTextTrim("Level"));
				if (Format.getInstance().isNotNullOrEmpty(cabinLevel)) {
					if (Integer.parseInt(cabinItem.getSeat().trim()) > 0
							&& cabinItem.getLevel().equals(cabinLevel)) {
						for (RateInfos rate : rates) {
							if ((rate.getAircom() == null)
									|| (!rate.getAircom().toString().contains(
											item.getAircom())))
								continue;
							if (rate.getCabins().toString().contains(
									cabinItem.getCode())) {
								if (rate.getIsUse().equals("1")) {
									cabinItem.setRate(rate);
									break;
								}
								if (!rate.getFlightNos().toString().contains(
										item.getFlightNo())) {
									cabinItem.setRate(rate);
									break;
								}
							}
						}
						if (cabinItem.getRate() != null) {
							if (cabinLevel != null
									&& cabinLevel.equals(cabinItem.getLevel())) {
								cabinList.add(cabinItem);
							} else {
								cabinList.add(cabinItem);
							}
						}
					}
				} else {
					if (Integer.parseInt(cabinItem.getSeat().trim()) > 0) {
						for (RateInfos rate : rates) {
							if ((rate.getAircom() == null)
									|| (!rate.getAircom().toString().contains(
											item.getAircom())))
								continue;
							if (rate.getCabins().toString().contains(
									cabinItem.getCode())) {
								if (rate.getIsUse().equals("1")) {
									cabinItem.setRate(rate);
									break;
								}
								if (!rate.getFlightNos().toString().contains(
										item.getFlightNo())) {
									cabinItem.setRate(rate);
									break;
								}
							}
						}
						if (cabinItem.getRate() != null) {
							if (cabinLevel != null
									&& cabinLevel.equals(cabinItem.getLevel())) {
								cabinList.add(cabinItem);
							} else {
								cabinList.add(cabinItem);
							}
						}
					}
				}
				cabinItem = null;
			}
			item.setCabinList(cabinList);
			cabinList = null;
		}
		return item;
	}

	/**
	 * 查询航班信息
	 * 
	 * @param query
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	private String returnWebServiceResult(AirQuery query)
			throws UnsupportedEncodingException, IOException {
		TreeMap treemap = xfm.returnPublicPostData(AirParam.FLIGHT.toString());
		treemap.put("scity", query.getFromCity());
		treemap.put("ecity", query.getToCity());
		treemap.put("sdate", query.getFromDate());
		String sign = verify.returnAirMd5Hex(treemap);
		treemap.put("sign", sign);
		result = WebServicesSub.getInstance().returnResult(treemap);
		return result;
	}
}
